<template>
  <div class="bianji">
    <!--    编辑、新增线索-->
    <div>
      <el-row style="padding: 15px">获客线索</el-row>
      <hr/>
      <div style="margin-top: 30px">
        <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="160px">
          <el-row>
            <el-col :span="13">
              <el-form-item label="公司:" prop="cucGather">
                <el-input v-model="ruleForm.cucGather" style="width: 255px"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="11">
              <el-form-item label="联系人:" prop="cucLinkName">
                <el-input v-model="ruleForm.cucLinkName" style="width: 255px"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="13">
              <el-form-item label="对应客户:" prop="customerByCustomId.cusName">
                <el-input v-on:click.native="cus=true" v-model="ruleForm.customerByCustomId.cusName" title="请点击选择" style="width: 255px"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="11">
              <el-form-item label="联系电话:" prop="cucLinkPhone"><!--只能输入数字正则 -->
                <el-input v-model="ruleForm.cucLinkPhone" oninput="value=value.replace(/[^\d.]/g,'')" style="width: 255px"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="13">
              <el-form-item label="地址:" prop="cuclinkArea">
                <v-distpicker :province="ruleForm.cuclinkProvince" @province="changeProvince"
                              :city="ruleForm.cuclinkCity" @city="changeCity"
                              :area="ruleForm.cuclinkArea" @area="changeArea" @selected="changeAll"
                              class="distpicker-address-wrapper"></v-distpicker>
              </el-form-item>
            </el-col>
            <el-col :span="11">
              <el-form-item label="详细地址:" prop="cuclinkXxaddress">
                <el-input v-model="ruleForm.cuclinkXxaddress" style="width: 255px"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="21">
              <el-form-item label="需求:" prop="cucXqinfo">
                <el-input type="textarea" v-model="ruleForm.cucXqinfo"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="21">
              <el-form-item label="备注:" prop="cucRemark">
                <el-input type="textarea" v-model="ruleForm.cucRemark"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </div>
      <!--          按钮-->
      <el-button type="primary" style="margin-left: 76%;margin-top: 40px;margin-bottom: 30px" @click="saveConfirm('ruleForm')">确定</el-button>
      <router-link :to="{path:'/culuechi'}">
        <el-button style="margin-left: 2%;">取消</el-button>
      </router-link>
    </div>

    <!--      选择客户弹框-->
    <el-dialog
      title="选择客户"
      :visible.sync="cus">
      <el-row>
        <el-col :span="4">
          <el-input
            placeholder="请输入客户名称" @change="serchCustomer" clearable onKeypress="javascript:if(event.keyCode == 32)event.returnValue = false;" style="width: 180px;margin-left: 420px;cursor: pointer"
            v-model="input4" suffix-icon="el-icon-search" size="small">
          </el-input>
        </el-col>
      </el-row>
      <el-row>
        <el-col>
          <el-table ref="multipleTable" :data="cusTable" style="width: 100%" height="250">
            <el-table-column width="55" fixed>
              <template slot-scope="scope" >
                <el-radio v-model="radio" :label="scope.row.customId" @change="getCustomerRow(scope.row)">
                  {{''}}
                </el-radio>
              </template>
            </el-table-column>

            <el-table-column fixed prop="cusName" label="客户名称" width="180">
            </el-table-column>

            <el-table-column prop="customEmpid.empName" label="负责人">
            </el-table-column>

            <el-table-column prop="typeId.typeName" label="客户类型" width="120">
            </el-table-column>

            <el-table-column prop="customTime" label="创建日期" width="180">
              <template slot-scope="s">
                {{ s.row.customTime | formatDate}}
              </template>
            </el-table-column>
          </el-table>
          <!--        分页-->
          <div class="page">
            <el-pagination
              :page-sizes="sizes"
              layout="total, sizes, prev, pager, next, jumper"
              :total="totalSize"
              :page-size="pageSize"
              :current-page.sync="currPage"
              @current-change="pageChange"
              @size-change="sizeChange">
            </el-pagination>
          </div>
        </el-col>
      </el-row>
      <span slot="footer" class="dialog-footer">
         <el-button type="primary" @click="cusOK">确 定</el-button>
        <el-button @click="cus = false">取 消</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
  import VDistpicker from 'v-distpicker'
  import {formatTimeToStr} from '@/assets/format'
export default {
  inject: ['reload'],
  name: 'CulueAdd',
  components: { VDistpicker },
  data: function () {
    // 查询联系电话是否重复
    var checkedCucupPhone = (rule, value, callback) => {
      if(this.updateCucupPhone == value){
        // 如果修改联系人信息时没有修改联系人电话，就不做校验
        callback();
      }else{
        this.$axios.get("http://localhost:8088/vue/select-cucupphone",{params:{cucLinkPhone:value}})
          .then(v=>{
            console.log(v.data)
            if(v.data != null && v.data != ""){
              callback(new Error("联系电话重复！请重新输入"))
            }else{
              callback()
            }
          }).catch()
      }
    };
    var checkAdress = (rule, value, callback) => {
      if (this.area=="区" || this.area==undefined) {
        return callback(new Error('地址不能为空'));
      }
    };
    return {
      updateCucupPhone:'',//校验联系电话
      ruleForm: [],
      rules: {
        cucGather: [//公司
          { required: true, message: '请输入公司名称', trigger: 'change' },
        ],
        'customerByCustomId.cusName': [//选择客户
          { required: true, message: '请选择对应客户', trigger: 'change' }
        ],
        cucLinkName: [//联系人
          { required: true, message: '请输入联系人', trigger: 'change' }
        ],
        cucLinkPhone:[
          { required:true, message: '请输入联系电话', trigger: 'change'},
          { pattern: /^1[3456789]\d{9}$/,message: '请输入正确的联系电话', trigger:'change'},
          {validator:checkedCucupPhone,trigger: 'change'}
        ],
        cuclinkArea: [
          { required:true, message: '请输入联系地址', trigger: 'change'},
          // {validator:checkAdress, trigger: 'change'}
        ],
        cuclinkXxaddress:[
          { required:true, message: '请输入详细地址', trigger: 'change'},
        ]
      },
      customer:[], //新增线索时选中添加的客户对象
      cName:'',//选中的客户的客户名
      cus: false, // 选择客户弹框
      radio: '', // 单选框
      input4: '', // 客户的搜索框
      totalSize: 0, //     总条数
      currPage: 1, //     默认第一页
      pageSize: 0, //      页大小
      sizes: [10,20,30,40], // 客户页大小数组
      cusTable: [], //客户列表
      area:'',//校验地址
    }
  },
  created: function () {
    this.pageSize = this.sizes[0] // 默认第一个页大小
    this.init(this.currPage, this.pageSize) // 初始化客户
    if(this.$route.path != null && this.$route.path != ""){
      this.clearForm()
    }
    if(this.$route.query.culue != null && this.$route.query.culue != ""){
      this.ruleForm=this.$route.query.culue
      this.updateCucupPhone=this.ruleForm.cucLinkPhone
    }
  },
  methods: {
    init (currPage, pageSize, input4) {
      this.$axios.get('http://localhost:8088/vue/have-type', {params: {page: currPage, size: pageSize, cusName: input4}})
        .then(v => {
          this.cusTable = v.data.rows
          this.totalSize = v.data.total
        })
        .catch(v => {
          alert('访问失败！' + v.data)
        })
    },
    pageChange (page) { // 客户切换页码
      this.init(page, this.pageSize, this.input4)
    },
    sizeChange (pageSize) { // 客户页大小改变
      this.init(1, pageSize, this.input4)
      this.pageSize = pageSize
    },
    serchCustomer () { // 客户模糊查询、条件查询
      this.init(1, this.pageSize, this.input4)
    },
    //单选框选中的行
    getCustomerRow(val){
      this.customer=[];//单选框每次只能选择一个，所以每次选中之前要先清空
      this.customer.push(val);
      this.cName=this.customer[0].cusName
      window.console.log(this.customer[0].customId)
    },
    cusOK(){ // 确定选中客户
      if(this.customer==null || this.customer==""){
        this.$message("请选择客户")
      }else {
        this.ruleForm.customerByCustomId.cusName=this.customer[0].cusName
        this.ruleForm.customerByCustomId.customId=this.customer[0].customId
        this.cus=false
      }
    },
    changeProvince(province){//省
      this.ruleForm.cuclinkProvince=province.value
    },
    changeCity(city){//市
      this.ruleForm.cuclinkCity=city.value
    },
    changeArea(area){//区
      this.ruleForm.cuclinkArea=area.value
      this.area=this.ruleForm.cuclinkArea
    },
    changeAll(all){//选中区触发
      console.log(all)
    },
    saveConfirm (formName) { // 确定新增或修改线索
      this.$refs[formName].validate((valid) => {
        if (valid) {//如果通过验证
          var cuclue = JSON.stringify({cuclue: this.ruleForm})
          var id = JSON.parse(sessionStorage.getItem('user')).employeesId;//用户id
          this.$axios.post("http://localhost:8088/vue/save-cuclue", this.qs.stringify({cuclue: cuclue,empId:id}))
            .then(() => {
              this.edit = false
              if (this.ruleForm.cucId != "" && this.ruleForm.cucId != null && this.ruleForm.cucId != 0) {
                this.$message.success('编辑成功')
              } else {
                this.$message.success('新增成功')
              }
              this.reload()
              this.clearForm()
              this.$router.push({
                path: '/culuechi',
              })
            })
            .catch()
        } else {
          console.log('error submit!!');
          return false;
        }
      });
    },
    clearForm(){
      this.ruleForm={
        cucId:'',
        cucType: '录入', // 来源
        customerByCustomId:{
          customId:'',
          cusName:'',
        }, // 对应客户
        cucGather: '', // 公司
        cucLinkName:'',//联系人
        cucLinkPhone: '', // 联系电话
        cuclinkProvince:'',//联系地址
        cuclinkCity:'',
        cuclinkArea:'',
        cucXqinfo: '',//需求
        cucRemark: ''//备注
      }
    }
  },
  watch:{
    $route(){
      if(this.$route.path != null && this.$route.path != ""){
        this.clearForm()
      }
      if(this.$route.query.culue != null && this.$route.query.culue != ""){
        this.ruleForm=this.$route.query.culue
      }
    }
  },
  filters: {// 日期格式化
    formatDate: function (time) {
      if (time != null && time != '') {
        var date = new Date(time)
        return formatTimeToStr(date, 'yyyy-MM-dd hh:mm:ss')
      } else {
        return ''
      }
    }
  }
}
</script>

<style scoped>
  .bianji{
    border:1px solid #ccc;
    width:100%;
    min-height: 640px;
    background: white;
    border-radius: 5px;
    box-shadow:#ccc 0px 0px 10px;
    overflow:hidden;
  }

  .page{
    margin-top:10px;
    float: right;
    margin-right: 20px;
  }
</style>
<style>
  .distpicker-address-wrapper select {
    width: 95px;
  }
</style>
